<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>混合数据模式测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
        }
        h2 {
            margin-top: 0;
            color: #555;
        }
        button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 8px 16px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        pre {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
        }
        .success {
            color: green;
        }
        .error {
            color: red;
        }
        .warning {
            color: orange;
        }
        .api-status {
            margin-top: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>混合数据模式测试</h1>
        
        <div class="card">
            <h2>当前混合数据模式设置</h2>
            <p>混合模式启用状态: <span id="hybrid-mode-status">检查中...</span></p>
            <p>失败回退到模拟数据: <span id="fallback-status">检查中...</span></p>
            <p>显示模拟数据标记: <span id="indicator-status">检查中...</span></p>
            <button id="toggle-hybrid-mode">切换混合模式</button>
            <button id="toggle-fallback">切换失败回退设置</button>
        </div>
        
        <div class="card">
            <h2>API 连接测试</h2>
            <button id="test-api">测试 API 连接</button>
            <div class="api-status" id="api-status">未测试</div>
        </div>
        
        <div class="card">
            <h2>测试 Dashboard 混合 API</h2>
            <button id="test-dashboard-overview">Dashboard 概览</button>
            <button id="test-alerts">告警数据</button>
            <button id="test-device-status">设备状态</button>
            <pre id="api-result">// 点击按钮测试API</pre>
        </div>
        
        <div class="card">
            <h2>CORS 错误模拟与处理</h2>
            <button id="simulate-cors-error">模拟 CORS 错误</button>
            <button id="clear-cors-error">清除 CORS 错误</button>
            <p>上次 CORS 错误: <span id="last-cors-error">无</span></p>
        </div>
    </div>
    
    <script>
        // 更新混合模式状态显示
        function updateHybridModeStatus() {
            const useMockData = localStorage.getItem('useMockData') === 'true';
            document.getElementById('hybrid-mode-status').textContent = useMockData ? '已启用' : '已禁用';
            document.getElementById('hybrid-mode-status').className = useMockData ? 'success' : 'warning';
            
            // 假设默认启用失败回退和指示器
            document.getElementById('fallback-status').textContent = '已启用';
            document.getElementById('fallback-status').className = 'success';
            
            document.getElementById('indicator-status').textContent = '已启用';
            document.getElementById('indicator-status').className = 'success';
        }
        
        // 测试API连接
        async function testApiConnection() {
            const apiStatusElement = document.getElementById('api-status');
            apiStatusElement.textContent = '测试中...';
            apiStatusElement.className = '';
            
            try {
                const response = await fetch('https://zmyzmy.xin/api/status', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    apiStatusElement.textContent = '连接成功!';
                    apiStatusElement.className = 'success';
                } else {
                    apiStatusElement.textContent = `连接失败: ${response.status} ${response.statusText}`;
                    apiStatusElement.className = 'error';
                }
            } catch (error) {
                apiStatusElement.textContent = `连接错误: ${error.message}`;
                apiStatusElement.className = 'error';
                
                // 检查是否是CORS错误
                if (error.message.includes('CORS') || error.message.includes('cross-origin')) {
                    apiStatusElement.textContent += ' (CORS 错误)';
                }
            }
        }
        
        // 测试特定API端点
        async function testApi(endpoint) {
            const resultElement = document.getElementById('api-result');
            resultElement.textContent = '加载中...';
            
            try {
                const response = await fetch(`https://zmyzmy.xin/api/${endpoint}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    resultElement.textContent = JSON.stringify(data, null, 2);
                } else {
                    resultElement.textContent = `错误: ${response.status} ${response.statusText}`;
                }
            } catch (error) {
                resultElement.textContent = `请求错误: ${error.message}\n\n模拟数据将在实际应用中使用`;
                
                // 模拟混合模式的回退行为
                if (endpoint === 'dashboard/overview') {
                    resultElement.textContent += '\n\n模拟数据示例:\n' + JSON.stringify({
                        deviceCount: 42,
                        onlineCount: 35,
                        onlineRate: '83%',
                        alarmCount: 8,
                        alarmTrend: -5,
                        errorCount: 3
                    }, null, 2);
                }
            }
        }
        
        // 模拟CORS错误
        function simulateCorsError() {
            const corsError = {
                path: '/dashboard/overview',
                timestamp: new Date().toISOString(),
                message: 'Access to fetch at \'https://zmyzmy.xin/api/dashboard/overview\' from origin \'http://localhost:8080\' has been blocked by CORS policy'
            };
            
            localStorage.setItem('lastCorsError', JSON.stringify(corsError));
            updateCorsErrorStatus();
        }
        
        // 清除CORS错误
        function clearCorsError() {
            localStorage.removeItem('lastCorsError');
            updateCorsErrorStatus();
        }
        
        // 更新CORS错误状态显示
        function updateCorsErrorStatus() {
            const corsErrorElement = document.getElementById('last-cors-error');
            const lastCorsError = localStorage.getItem('lastCorsError');
            
            if (lastCorsError) {
                try {
                    const error = JSON.parse(lastCorsError);
                    corsErrorElement.textContent = `${error.path} (${new Date(error.timestamp).toLocaleString()})`;
                    corsErrorElement.className = 'error';
                } catch (e) {
                    corsErrorElement.textContent = '错误格式无效';
                    corsErrorElement.className = 'warning';
                }
            } else {
                corsErrorElement.textContent = '无';
                corsErrorElement.className = '';
            }
        }
        
        // 绑定事件处理程序
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化状态显示
            updateHybridModeStatus();
            updateCorsErrorStatus();
            
            // 绑定按钮事件
            document.getElementById('toggle-hybrid-mode').addEventListener('click', () => {
                const currentValue = localStorage.getItem('useMockData') === 'true';
                localStorage.setItem('useMockData', (!currentValue).toString());
                updateHybridModeStatus();
                alert(`混合模式已${!currentValue ? '启用' : '禁用'}`);
            });
            
            document.getElementById('test-api').addEventListener('click', testApiConnection);
            
            document.getElementById('test-dashboard-overview').addEventListener('click', () => {
                testApi('dashboard/overview');
            });
            
            document.getElementById('test-alerts').addEventListener('click', () => {
                testApi('dashboard/alerts');
            });
            
            document.getElementById('test-device-status').addEventListener('click', () => {
                testApi('dashboard/device-status');
            });
            
            document.getElementById('simulate-cors-error').addEventListener('click', simulateCorsError);
            document.getElementById('clear-cors-error').addEventListener('click', clearCorsError);
        });
    </script>
</body>
</html>
